import subprocess
import argparse

def get_pctl(a, p):
	i = int(len(a) * p)
	return a[i]

def get_output(filename, nhost):
	dcn_output = []
	wan_output = []
	border = nhost / 2
	with open(filename, 'r') as f:
		for line in f:
			sid = (int(line.split()[0], 16) >> 8) & 0xffff
			did = (int(line.split()[1], 16) >> 8) & 0xffff
			flow_size = int(line.split()[4])
			ratio = float(line.split()[6])/ float(line.split()[7])
			ratio = 1 if ratio < 1 else ratio
			if (sid < border and did < border) or (sid >= border and did >= border):
				dcn_output.append([flow_size, ratio])
			else:
				wan_output.append([flow_size, ratio])
	dcn_output.sort(key=lambda x: x[0])
	wan_output.sort(key=lambda x: x[0])
	print("Dcn flow count: %d\nWan flow count: %d\n"%(len(dcn_output), len(wan_output)))
	return dcn_output, wan_output

def get_res(output, step):
	res = [[i/100.] for i in range(0, 100, step)]
	n = len(output)
	for i in range(0, 100, step):
		l = i * n / 100
		r = (i + step) * n / 100
		fct = sorted(map(lambda x: x[1], output[l:r]))
		res[i/step].append(output[r-1][0])
		res[i/step].append(get_pctl(fct, 0.5))
		res[i/step].append(get_pctl(fct, 0.95))
		res[i/step].append(get_pctl(fct, 0.99))
	return res

if __name__=="__main__":
	parser = argparse.ArgumentParser(description='')
	parser.add_argument('-p', dest='prefix', action='store', default='fct_fat', help="Specify the prefix of the fct file. Usually like fct_<topology>_<trace>")
	parser.add_argument('-s', dest='step', action='store', default='5')
	parser.add_argument('-T', dest='time_limit', action='store', type=int, default=3000000000, help="only consider flows that finish before T")
	parser.add_argument('-b', dest='bw', action='store', type=int, default=25, help="bandwidth of edge link (Gbps)")
	parser.add_argument('-i', dest='id', action='store', type=int, default=0, help="id of the simulation")
	parser.add_argument('-n', dest='nhost', action='store', type=int, default=0, help="number of hosts in the topology")
	args = parser.parse_args()

	time_limit = args.time_limit
	id = args.id
	nhost = args.nhost

	# Please list all the cc (together with parameters) that you want to compare.
	# For example, here we list two CC: 1. HPCC-PINT with utgt=95,AI=50Mbps,pint_log_base=1.05,pint_prob=1; 2. HPCC with utgt=95,ai=50Mbps.
	# For the exact naming, please check ../simulation/mix/fct_*.txt output by the simulation.
	CCs = [
		'dcqcn',
	]

	step = int(args.step)
	for cc in CCs:
		file = "../simulation/output/%s_%s_%s.txt"%(args.prefix, cc, id)

		dcn_output, wan_output = get_output(file, nhost)
		dcn_res = get_res(dcn_output, step)
		# wan_res = get_res(wan_output, step)
		for item in dcn_res:
			line = "%.3f %d\t %.3f %.3f %.3f"%(item[0], item[1], item[2], item[3], item[4])
			print(line)